<?php

namespace Blog\App\Model;

use Hx\App;

/**
 * 分类操作类
 * Class Category
 * @package Blog\App\Model
 */
class Category {

    /**
     * 数据库对象
     * @var \Hx\Db
     */
    private $db;

    /**
     * 构造函数
     */
    public function __construct() {
        $this->db = App::Db();
    }

    /**
     * 获取所有分类
     * @return mixed
     */
    public function getAll() {
        $sql = App::Sql('HxSite_Category', 'id,name,keyString,nodeCount,createDate')
            ->where('status = "public"')
            ->order('nodeCount DESC')
            ->select();
        return $this->db->queryAll($sql);
    }

    /**
     * 获取一个分类
     * @param string $key
     * @param string $value
     * @return mixed
     */
    public function getOne($key, $value) {
        $sql = App::Sql('HxSite_Category')
            ->where('status = "public"')
            ->where($key . ' = :' . $key)
            ->select();
        return $this->db->query($sql, array($key => $value));
    }

    /**
     * 更新分类下文章计数
     */
    public function updateCount() {
        $sql = App::Sql('HxSite_Category', 'nodeCount')
            ->update();
        $sql2 = App::Sql('HxSite_Node AS N')
            ->where('N.status = "public" AND N.nodeType="blog"')
            ->where('HxSite_Category.id = N.categoryId')
            ->count();
        $sql = str_replace(':nodeCount', '(' . $sql2 . ')', $sql);
        $this->db->exec($sql);
    }
}